package controllers.order;

import java.util.Date;

import models.Order;
import models.OrderItem;
import models.User;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import controllers.routes;
import controllers.buy.Cart;
import controllers.user.UserController;

public class OrderController extends Controller {

	static Form<Order> orderForm = form(Order.class);

	public static Result orders(User currentUser) {
		return ok(views.html.order.orders.render(Order
				.ordersByUser(currentUser)));
	}

	public static Result buy() {
		String useremail = session("currentUserEmail");
		User user = UserController.getCurrentUser();
		if (null != user && user.getPriv("user")) {

			Cart usercart = Cart.getUserCart(useremail);

			if (usercart.size() > 0) {
				Order o = new Order();
				o.setUser(UserController.getCurrentUser());
				Date date = new Date();
				o.setDate(date);
				for (OrderItem oi : usercart) {
					o.addToOrderItems(oi);
				}
				Order.create(o);
				usercart.clear();
				return orders(UserController.getCurrentUser());
			} else {
				return redirect(routes.Application.index());
			}
		} else {
			return redirect(controllers.user.routes.UserController.logIn());
		}

	}
}
